class Solution {
public:
    int trap(vector<int>& height) {
        int n = height.size();
        if (n <= 2) return 0; 
        int left = 0, right = n - 1;
        int leftMax = height[left], rightMax = height[right];
        int result = 0;
        while (left < right) {
            if (leftMax < rightMax)}
                result += leftMax - height[left];
                left++;
                leftMax = max(leftMax, height[left]);
            } else {
                result += rightMax - height[right];
                right--;
                rightMax = max(rightMax, height[right]);
            }
        }
        return result;
    }
};